package nc.bs.oa.servlet;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.bc.pub.util.SysParaInitQuery;
import nc.vo.oa.msg.IMessageIntegrateOAService;
import nccloud.utils.riart.MessageLogger;

@SuppressWarnings("restriction")
public class OpenMessage extends HttpServlet implements
        IHttpServletAdaptor{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private BaseDAO baseDAO;
    private IMessageIntegrateOAService oaService;


    public BaseDAO getBaseDAO() {
        if(null == baseDAO) {
            baseDAO = new BaseDAO(InvocationInfoProxy.getInstance().getUserDataSource());
//			baseDAO = new BaseDAO();
        }
        return baseDAO;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doAction(req, resp);
    }

    @SuppressWarnings("restriction")
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doAction(req, resp);
    }
    @SuppressWarnings("restriction")
    @Override
    public void doAction(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        MessageLogger.info("##企业微信#进请求HOPG系统PC端#【nc.bs.oa.servlet.OpenMessage】.");
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        StringBuffer url1=request.getRequestURL();
        //获取ip:port
        String a[]=url1.toString().split("/");
        PrintWriter pw = response.getWriter();
        InputStream is = new BufferedInputStream(request.getInputStream());
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        int b = 0;
        while((b = is.read()) != -1) {
            byteOut.write(b);
        }
        byte[] temp = byteOut.toByteArray();
        String json = new String(temp, "UTF-8");
        JSONObject param = JSONObject.parseObject(json);
        MessageLogger.info("第三方系统单点NCC，参数为：【"+param+"】");
        if(param == null) {
            pw.println("请求参数不能为空" );
            return;
        }
        //获取回调地址中附加的coder
        String code = param.getString("userCode");
        if(code==null||"".equals(code)){
            pw.println("获取userCode为空" );
            return;
        }
        try {
            NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(),"pfxx".getBytes());
//			String dataSource = MsgSyncUtils.queryGroupSysParam("BD900");
            InvocationInfoProxy.getInstance().setUserDataSource("yonyou");
            MessageLogger.info("第三方请求NCC调用的方法【OpenMessage】模拟登陆完成：数据源="+"yonyou");
            String msgpk = param.getString("msgpk");
            String client_id = param.getString("client_id");
            String client_security = param.getString("client_security");
            String sql = "select pk_oauth_security from sm_oauth_security where client_id = '"+client_id+"' and client_security  = '"+client_security+"'";
            Object result = getBaseDAO().executeQuery(sql, new ColumnProcessor());
            if(result == null) {
                pw.println("请求参数中 client_id 或 client_security 参数有误或为空！！！ " );
                return;
            }
            String type = param.getString("funType");
            MessageLogger.info("开始准备处理NCC的单点地址。。。。。。。。。。。。");
//
            String url = NCLocator.getInstance().lookup(IMessageIntegrateOAService.class).getOpenMsgUrl(code, msgpk,type);
            if(url==null||"".equals(url)){
                pw.println("消息已读状态已同步NCC" );
                return;
            }
            MessageLogger.info("第三方 系统单点NCC结束：OA重定向地址为：【"+url+"】.........");
            pw.print(url);
        } catch (Exception e) {
            MessageLogger.error("第三方系统 单点NCC失败：失败原因：" + e.getMessage());
            pw.println("第三方系统 单点NCC失败：失败原因：" + e.getMessage());
            return;
        }

    }

    private String getSysInitString(String name) {
        return SysParaInitQuery.getParaString("GLOBLE00000000000000", name);
    }

    public IMessageIntegrateOAService getOaService() {
        if(null == oaService) {
            oaService = NCLocator.getInstance().lookup(IMessageIntegrateOAService.class);
        }
        return oaService;
    }


}